package cn.byapps.attendance.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import cn.byapps.attendance.entity.Student;
import cn.byapps.attendance.entity.Teacher;
import cn.byapps.attendance.service.LoginService;

@Controller
@SessionAttributes({ "loginUser", "loginAdmin" })
public class LoginController {

	@Resource
	private LoginService loginService;

	/*
	 * 主页
	 */
	@RequestMapping("index")
	public String index() {
		return "system/index";
	}

	@RequestMapping("userindex")
	public String userindex() {
		return "system/userindex";
	}

	/*
	 * 登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.GET)
	public String login() {
		return "system/login";
	}

	/*
	 * 登录
	 */
	@RequestMapping(value = "login", method = RequestMethod.POST)
	public String login(String id, String password, Model model) {

		Object object = loginService.getLoginObject(id, password);
		if (object == null)
			return "system/login";
		if (object instanceof Teacher) {
			model.addAttribute("loginAdmin", object);
			return "redirect:index";
		}
		if (object instanceof Student) {
			model.addAttribute("loginUser", object);
			return "redirect:userindex";
		}
		return "system/login";
	}

	/*
	 * 退出
	 */
	@RequestMapping(value = "logout", method = RequestMethod.GET)
	public String logout(HttpSession session, Model model) {
		model.asMap().remove("loginAdmin");
		session.removeAttribute("loginAdmin");
		return "redirect:login";
	}
	@RequestMapping(value = "userlogout", method = RequestMethod.GET)
	public String logoutUser(HttpSession session, Model model) {
		model.asMap().remove("loginUser");
		session.removeAttribute("loginUser");
		return "redirect:login";
	}
}
